import { isOk } from './../../support/untils/bcrypt';
import { hashPassword } from 'src/support/untils/bcrypt';
import { UpdatePsdByTokenDto } from './Dto/updatePsdByToken.dto';
import { UpdatePsdDto } from './Dto/updatePsd.dto';
import { UpdateUserInfoDto } from './Dto/updateUser.dto';
import { RemoveUserByIdDto } from './Dto/removeUser.dto';
import { FindOneUserByIdDto } from './Dto/findOneById.dto';
import { AuthGuard } from '@nestjs/passport';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import {
  Body,
  Controller,
  Delete,
  Get,
  Post,
  Put,
  Query,
  Request,
  UseGuards,
} from '@nestjs/common';
import { AuthService } from 'src/auth/auth.service';
import { UserService } from './user.service';
import { ApiResult } from 'src/config';
import { CreateUserDto } from './Dto/createUser.dto';
import { FindAllUserDto } from './Dto/findAll.dto';
import { UpdateUserByTokenDto } from './Dto/updateUserByToken.dto';
@Controller('user')
@ApiTags('用户')
export class UserController {
  constructor(
    private readonly usersService: UserService,
    private readonly authService: AuthService,
  ) {}

  @ApiOperation({ summary: '用户注册' })
  @Post('register')
  async register(@Body() createUserDto: CreateUserDto): Promise<ApiResult> {
    const isRegister = await this.usersService.findOne({
      username: createUserDto.username,
    });
    if (isRegister) {
      return ApiResult.SUCCESS(null, -1, '此账号已被注册');
    } else {
      const result = await this.usersService.createOne(createUserDto);
      if (result.user_id) {
        return ApiResult.SUCCESS(null, 0, '注册成功!');
      }
    }
  }

  @ApiOperation({ summary: '用户登录' })
  @Post('login')
  async login(@Body() createUserDto: CreateUserDto): Promise<ApiResult> {
    const result = await this.usersService.findOne({
      username: createUserDto.username,
    });
    if (result) {
      console.log(result);
      console.log(isOk(createUserDto.password, result.password));

      if (!isOk(createUserDto.password, result.password)) {
        return ApiResult.ERROR(-2, '密码错误!');
      }
      const data = await this.authService.getToken(result);
      return ApiResult.SUCCESS(
        { token: 'Bearer ' + data.token },
        0,
        '登陆成功!',
      );
    } else {
      return ApiResult.ERROR(-2, '为查询到此账号!');
    }
  }

  @ApiOperation({ summary: '获取个人信息-用户端' })
  @Get('tokenToInfo')
  @UseGuards(AuthGuard())
  async tokenToInfo(@Request() request): Promise<ApiResult> {
    const { user_id } = request.user;
    return ApiResult.SUCCESS(await this.usersService.findOneById(user_id));
  }

  @ApiOperation({ summary: '添加用户' })
  @Post('addUser')
  async addUser(@Body() createUserDto: CreateUserDto): Promise<ApiResult> {
    const result = await this.usersService.findOne({
      username: createUserDto.username,
    });
    if (result) {
      return ApiResult.ERROR(-2, '已存在账户名!');
    } else {
      const res = await this.usersService.createOne(createUserDto);
      return ApiResult.SUCCESS(res, 0, '创建成功!');
    }
  }

  @ApiOperation({ summary: '修改个人信息-用户端' })
  @Put('updateInfo')
  @UseGuards(AuthGuard())
  async updateMyInfo(
    @Request() request,
    @Body() updateUserByTokenDto: UpdateUserByTokenDto,
  ): Promise<ApiResult> {
    const { user_id } = request.user;
    const params = { ...updateUserByTokenDto, user_id };
    const result = await this.usersService.updateUser(params);
    return ApiResult.SUCCESS(result);
  }

  @ApiOperation({ summary: '修改密码-用户端' })
  @Put('updateMyPsd')
  @UseGuards(AuthGuard())
  async updateMyPsd(
    @Request() request,
    @Body() updatePsdByTokenDto: UpdatePsdByTokenDto,
  ): Promise<ApiResult> {
    const { user_id } = request.user;
    const { password, confirmPsd } = updatePsdByTokenDto;
    if (password !== confirmPsd) {
      return ApiResult.ERROR(-1, '两次输入的密码不正确');
    } else {
      const params = { user_id, password };
      const result = await this.usersService.updateUser(params);
      if (result) {
        return ApiResult.SUCCESS(null, 0, '修改成功！');
      }
    }
  }

  @ApiOperation({ summary: '获取所有用户信息' })
  @Post('list')
  @UseGuards(AuthGuard())
  async findAll(@Body() findAllUserDto: FindAllUserDto): Promise<ApiResult> {
    const data = await this.usersService.findAll(findAllUserDto);
    return ApiResult.SUCCESS(data);
  }

  @ApiOperation({ summary: '根据id查用户' })
  @Get('findOneById')
  @UseGuards(AuthGuard())
  async findOneById(
    @Query() findOneUserByIdDto: FindOneUserByIdDto,
  ): Promise<ApiResult> {
    const result = await this.usersService.findOneById(
      findOneUserByIdDto.user_id,
    );
    if (!result) {
      return ApiResult.ERROR(-1, '未查询到此人');
    }
    return ApiResult.SUCCESS(result);
  }

  @ApiOperation({ summary: '删除用户/批量删除用户' })
  @Delete('remove')
  @UseGuards(AuthGuard())
  async remove(
    @Body() removeUserByIdDto: RemoveUserByIdDto,
  ): Promise<ApiResult> {
    const { user_id } = removeUserByIdDto;
    const result = await this.usersService.removeUser(user_id);
    if (result.affected === user_id.length) {
      return ApiResult.SUCCESS('删除成功！');
    }
    return ApiResult.ERROR(-1, '删除失败！');
  }

  @ApiOperation({ summary: '根据Id修改用户信息' })
  @Put('update')
  @UseGuards(AuthGuard())
  async update(
    @Body() updateUserInfoDto: UpdateUserInfoDto,
  ): Promise<ApiResult> {
    const result = await this.usersService.updateUser(updateUserInfoDto);
    if (!result) {
      return ApiResult.ERROR(-1, '未查询到此用户信息！');
    }
    return ApiResult.SUCCESS(null, 0, '修改成功！');
  }

  @ApiOperation({ summary: '修改密码' })
  @Put('updatePsd')
  @UseGuards(AuthGuard())
  async updatePsd(
    @Request() request,
    @Body() updatePsdDto: UpdatePsdDto,
  ): Promise<ApiResult> {
    const { user_id, password, confirmPsd } = updatePsdDto;
    // 判断两次输入密码是否相同
    if (password !== confirmPsd) {
      return ApiResult.ERROR(-1, '两次输入的密码不正确');
    } else {
      const params = { user_id, password };
      const result = await this.usersService.updateUser(params);
      if (result) {
        return ApiResult.SUCCESS(null, 0, '修改成功！');
      } else {
        return ApiResult.ERROR(-1, '未查询到此人');
      }
    }
  }

  @ApiOperation({ summary: '统计用户数量' })
  @Get('count')
  @UseGuards(AuthGuard())
  async count(): Promise<ApiResult> {
    const result = await this.usersService.count();
    return ApiResult.SUCCESS({ count: result }, 0, '修改成功！');
  }
}
